package com.siqi.hr.system.custom.service;

import com.siqi.hr.common.utils.Const;
import com.siqi.hr.system.common.enums.OperationEnum;
import com.siqi.hr.system.custom.dao.intf.DbStructureDao;
import com.siqi.hr.system.custom.dao.intf.EntityRecordDao;
import com.siqi.hr.system.custom.entity.EntityOperation;
import com.siqi.hr.system.custom.entity.EntityRecord;
import com.siqi.hr.system.custom.utils.EntityUtils;
import com.siqi.hr.system.exception.DataExistInTableException;
import com.siqi.hr.system.exception.DeleteException;
import com.siqi.hr.system.organization.dao.intf.MenuDao;
import com.siqi.hr.system.organization.dao.intf.OrganizeDao;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 实体注册信息维护service层
 * @author    xiaogq
 * Created by xiaogoingqin on 2016/7/24.
 */
@Component("entityRecordService")
@Transactional(rollbackFor = { Exception.class },propagation = Propagation.REQUIRED)
public class EntityRecordService {
    private static final Logger logger = Logger.getLogger(EntityRecordService.class);

    @Autowired
    private EntityRecordDao entityRecordDao;

    @Autowired
    private DbStructureDao dbStructureDao;

    @Autowired
    private OrganizeDao organizeDao;

    @Autowired
    private MenuDao menuDao;

    /**
     * 获取实体注册表列表显示字段(xiaogq)
     *@return map
     */
    public Map<String, Object> queryEntityListColumns() {
        Map<String, Object> columnMap = new HashMap<String, Object>();
        StringBuffer columns = new StringBuffer();
        columns.append("<th data-field='position' data-checkbox='false'></th>");
        columns.append("<th data-field='operation' data-formatter='showColOperator'>操作</th>");
        columns.append("<th data-field='inchinese' data-sortable='true'>对象名称</th>");
        columns.append("<th data-field='belong_mudule'>所属模块</th>");
        columns.append("<th data-field='use_recyclebin'>使用回收站</th>");
        columns.append("<th data-field='define_field'>自定义属性</th>");
        columns.append("<th data-field='permission'>数据权限</th>");
        columns.append("<th data-field='define_stage_manager'>可定义工作流</th>");
        columns.append("<th data-field='define_approval'>可定义审批流</th>");
        columnMap.put("fields", "");
        columnMap.put("columns", columns);
        return columnMap;
    }

    /**
     * 查询系统设置模块对象管理列表页数据
     * @param systemEntity     是否是系统实体(true:是，false：否)
     * @return
     */
    public Map<String,Object> queryEntityData(boolean systemEntity) throws Exception{
        Map<String,Object> resultMap = new HashMap<String,Object>();
        List<Map<String, Object>> entitysData = entityRecordDao.getEntityRecords(systemEntity);
        //最终映射表格数据集合
        List<Map<String, Object>> resultDatas = new ArrayList<Map<String, Object>>();
        for (Map<String, Object> map : entitysData) {
            Map<String,Object> dataMaps = new HashMap<String,Object>();
            List<EntityOperation> optionList = new ArrayList<EntityOperation>();
            //所有实体默认都有编辑按钮
            EntityOperation entityEdit = new EntityOperation("编辑","entityUpdate","EntityRecord/entityRecordUpdateInit.do","glyphicon glyphicon-edit", OperationEnum.showColumn.name(),new EntityRecord(0));
            optionList.add(entityEdit);
            EntityOperation entityfieldList = new EntityOperation("属性设置","entityfieldList","FieldRecord/fieldRecordListInit.do","glyphicon glyphicon-cog",OperationEnum.showColumn.name(),new EntityRecord(0));
            optionList.add(entityfieldList);
            //获取实体是否有类型(0或null：没有类型的实体，1：有类型实体)
            String defineType = map.get("define_type") == null ? "0" : map.get("define_type").toString();
            if(Boolean.parseBoolean(defineType)){//如果是有类型的实体
                EntityOperation typeOper = new EntityOperation("类型查看","entityType","","glyphicon glyphicon-asterisk",OperationEnum.showColumn.name(),new EntityRecord(0));
                optionList.add(typeOper);
            }
            //获取是否是系统实体标识(0:否，1：是)
            String isSysEntity = map.get("system_entity") == null ? "0" : map.get("system_entity").toString();
            if(!Boolean.parseBoolean(isSysEntity)){//如果是自定义实体则添加删除按钮
                EntityOperation delEdit = new EntityOperation("删除实体","entityDelete","","glyphicon glyphicon-trash",OperationEnum.showColumn.name(),new EntityRecord(0));
                optionList.add(delEdit);
            }
            dataMaps.put("id",map.get("id"));
            dataMaps.put("operation",optionList);
            dataMaps.put("inchinese",map.get("inchinese"));
            dataMaps.put("position",map.get("position"));
            //获取当前实体所属模块
            String belongMudule = map.get("belong_mudule") == null ? "" : map.get("belong_mudule").toString();
            if(StringUtils.isNotBlank(belongMudule)){
                dataMaps.put("belong_mudule", EntityUtils.tranformLoginModule(belongMudule));

            }
            //获取实体是否使用回收站(0:否，1：是)
            String useRecyclebin = map.get("use_recyclebin") == null ? "0" : map.get("use_recyclebin").toString();
            if(Boolean.parseBoolean(useRecyclebin)){
                dataMaps.put("use_recyclebin","是");
            }else{
                dataMaps.put("use_recyclebin","否");
            }
            //获取实体是否可以添加自定义属性字段(0:否，1：是)
            String defineField = map.get("define_field") == null ? "0" : map.get("define_field").toString();
            if(Boolean.parseBoolean(defineField)){//如果实体可以添加自定义属性
                dataMaps.put("define_field","允许");
            }else{
                dataMaps.put("define_field","不允许");
            }
            //实体是否受权限控制(0:否,1:是)
            String permission = map.get("permission") == null ? "0" : map.get("permission").toString();
            if(Boolean.parseBoolean(permission)){//如果是受权限控制的实体
                dataMaps.put("permission","控制");
            }else{
                dataMaps.put("permission","不控制");
            }
            //实体是否可以定义工作流(0:否，1：是默认值为0)
            String workFlow = map.get("define_stage_manager") == null ? "0" : map.get("define_stage_manager").toString();
            if(Boolean.parseBoolean(workFlow)){//如果实体可以定义工作流
                dataMaps.put("define_stage_manager","是");
            }else{
                dataMaps.put("define_stage_manager","否");
            }
            //实体是否可以定义审批流(0:否，1：是默认值为0)
            String approval = map.get("define_approval") == null ? "0" : map.get("define_approval").toString();
            if(Boolean.parseBoolean(approval)){//如果实体可以定义审批流
                dataMaps.put("define_approval","是");
            }else{
                dataMaps.put("define_approval","否");
            }
            resultDatas.add(dataMaps);
        }
        resultMap.put(Const.ROWS, resultDatas);
        resultMap.put(Const.TOTAL, 100);
        return resultMap;
    }

    /**
     * 查询系统设置模块布局管理列表页数据
     * @param systemEntity     是否是系统实体(true:是，false：否)
     * @return
     */
    public Map<String, Object> queryEntityLayoutData(boolean systemEntity) throws Exception{
        Map<String, Object> resultMap = new HashMap<String,Object>();
        List<Map<String, Object>> entitysData = entityRecordDao.getEntityRecords(systemEntity);
        //最终映射表格数据集合
        List<Map<String,Object>> resultDatas = new ArrayList<Map<String,Object>>();
        for (Map<String, Object> map : entitysData) {
            Map<String,Object> dataMaps = new LinkedHashMap<String,Object>();
            List<EntityOperation> optionList = new ArrayList<EntityOperation>();
            //得到实体id
            int tableCode =  map.get("id") == null ? 0 : Integer.parseInt(map.get("id").toString());
            //所有实体默认都有编辑按钮
            EntityOperation editListLayout = new EntityOperation("布局","editEntityLayout","CommonOperation/fieldEmployeeLayout.do?position=List&isDefault=true","glyphicon glyphicon-list-alt",OperationEnum.showColumn.name(),new EntityRecord(0));
            EntityOperation editFilterLayout = new EntityOperation("过滤条件","editEntityLayout","CommonOperation/fieldEmployeeLayout.do?position=Filter&isDefault=true","glyphicon glyphicon-glass",OperationEnum.showColumn.name(),new EntityRecord(0));
            optionList.add(editListLayout);
            optionList.add(editFilterLayout);
            //获取实体是否有类型(0或null：没有类型的实体，1：有类型实体)
            String defineType = map.get("define_type") == null ? "0" : map.get("define_type").toString();
            if(Boolean.parseBoolean(defineType)){//如果是有类型的实体
//                EntityOperation typeOper = new EntityOperation("类型查看","entityType","","glyphicon glyphicon-asterisk",OperationEnum.showColumn.name(),new EntityRecord(0));
//                optionList.add(typeOper);
            }else{
//                EntityOperation editLayout = new EntityOperation("编辑页布局","editLayout","","glyphicon glyphicon-sound-stereo",OperationEnum.showColumn.name(),new EntityRecord(0));
//                EntityOperation showLayout = new EntityOperation("查看页布局","showLayout","","glyphicon glyphicon-sound-dolby",OperationEnum.showColumn.name(),new EntityRecord(0));
//                optionList.add(editLayout);
//                optionList.add(showLayout);
            }
            dataMaps.put("id",tableCode);
            dataMaps.put("operation",optionList);
            dataMaps.put("inchinese",map.get("inchinese"));
            dataMaps.put("position",map.get("position"));
            //获取当前实体所属模块
            String belongMudule = map.get("belong_mudule") == null ? "" : map.get("belong_mudule").toString();
            if(StringUtils.isNotBlank(belongMudule)){
                dataMaps.put("belong_mudule", EntityUtils.tranformLoginModule(belongMudule));

            }
            dataMaps.put("define_set","");
            //获取实体是否可以添加自定义属性字段(0:否，1：是)
            String defineField = map.get("define_field") == null ? "0" : map.get("define_field").toString();
            dataMaps.put("define_field","");
            if(Boolean.parseBoolean(defineField)){//如果实体可以添加自定义属性
                dataMaps.put("define_field","允许");
            }
            //实体是否受权限控制(0:否,1:是)
            String permission = map.get("permission") == null ? "0" : map.get("permission").toString();
            dataMaps.put("permission","");
            if(Boolean.parseBoolean(permission)){//如果是受权限控制的实体
                dataMaps.put("permission","控制");
            }
            //实体是否可以定义工作流(0:否，1：是默认值为0)
            String workFlow = map.get("define_stage_manager") == null ? "0" : map.get("define_stage_manager").toString();
            if(Boolean.parseBoolean(workFlow)){//如果实体可以定义工作流
                dataMaps.put("define_stage_manager","是");
            }else{
                dataMaps.put("define_stage_manager","否");
            }
            //实体是否可以定义审批流(0:否，1：是默认值为0)
            String approval = map.get("define_approval") == null ? "0" : map.get("define_approval").toString();
            if(Boolean.parseBoolean(approval)){//如果实体可以定义审批流
                dataMaps.put("define_approval","是");
            }else{
                dataMaps.put("define_approval","否");
            }
            resultDatas.add(dataMaps);
        }
        resultMap.put(Const.ROWS, resultDatas);
        resultMap.put(Const.TOTAL, 100);
        return resultMap;
    }

    /**
     * 根据实体id获取实体对象信息(xiaogq)
     * @param entityId         实体id
     * @return
     */
    public EntityRecord queryEntityRecordById(int entityId){
        EntityRecord entityRecord = new EntityRecord();
        try {
            entityRecord = entityRecordDao.queryEntityRecordById(entityId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return entityRecord;
    }

    /**
     * 添加一个自定义实体通用方法
     * @author xiaogq
     * @param entity             实体对象
     */
    public Integer addEntityRecord(EntityRecord entity) {
        //设置实体可以定义业务逻辑(0:否，1：是默认值为0)
        entity.setDefineLogic(true);
        //设置实体可以定义消息(0:否，1：是默认值为0)
        entity.setDefineMessage(true);
        //设置实体不是系统实体(0:不是系统实体，1：是默认值为0)
        entity.setSystemEntity(false);
        //是否在对象管理，布局管理中显示（true:不显示，false：显示）
        entity.setNodisplay(false);
        //实体是否可以添加属性字段
        entity.setDefineField(true);
        //实体记录添加与表创建
        int lens = dbStructureDao.addEntity(entity);
        Integer entityid = entity.getTableCode();
        if(lens > 0){
            //初始化实体菜单权限、操作权限 和 数据权限
            organizeDao.settingEntityPermissions(entity);
        }
        return entityid;
    }

    /**
     * 实体对象名称更新
     * @param entity  实体对象
     */
    public int updateEntityRecord(EntityRecord entity) {
        int counts = entityRecordDao.updateEntityRecord(entity);
        if(counts > 0){
            //修改该实体相关菜单名称
            if(!entity.getSystemEntity()){
                menuDao.updateEntityMenuName(entity.getTableCode(), entity.getInchinese());
            }
        }
        return counts;
    }

    /**
     * 删除自定义实体
     * @author xiaogq
     * @param entityId  实体id
     * @throws DeleteException     自定义异常
     */
    public void deleteEntityRecord(Integer entityId) throws DeleteException {
        boolean b = entityRecordDao.tableExistedInDatabase(entityId);
        //如果不存在实体表，就只删除注册信息
        if(!b){
            entityRecordDao.deleteEntityRecord(entityId);
            return ;
        }
        //如果实体中有记录就不删除
        int count = entityRecordDao.getEntityTableRecodeCount(entityId);
        if(count > 0 ){
            throw new DataExistInTableException();
        }
        dbStructureDao.deleteEntity(entityId);
    }

    /**
     * 得到所有可以引用的实体
     * @author xiaogq
     * @return
     */
    public List<EntityRecord> getCanQuoteEntity(boolean bool) {
        return entityRecordDao.getCanQuoteEntity(bool);
    }

    /**
     * 查询所有受权限控制实体的id及中文名称
     * @author          xiaogq
     * @param bool     true:实体受权限控制，false：实体不受权限控制
     * @return
     */
    public List<EntityRecord> queryPmsEntity(boolean bool) {
        String sql = " select table_code,name,inchinese from sys_custom_entity where permission = "+bool;
        return entityRecordDao.queryPmsEntity(bool);
    }

}
